using System;
using System.Collections.Generic;

namespace MIMPWinForms
{
    /// <summary>
    /// Used to pass shared services between different components.
    /// </summary>
    public class ServiceProvider : IServiceProvider
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        
        Dictionary<Type, object> services = new Dictionary<Type, object>();


        /// <summary>
        /// Adds a new service to the collection.
        /// </summary>
        public void AddService<T>(T service) {
            if (log.IsInfoEnabled) log.Info("Entered AddService");
            if (log.IsDebugEnabled) log.Debug("Adding: " + service.ToString());
            services.Add(typeof(T), service);
            if (log.IsInfoEnabled) log.Info("Exiting AddService");
        }


        /// <summary>
        /// Looks up the specified service.
        /// </summary>
        public object GetService(Type serviceType) {
            if (log.IsInfoEnabled) log.Info("Entered GetService");
            object service;

            services.TryGetValue(serviceType, out service);
            if (log.IsDebugEnabled) log.Debug("Retrieved service: " + service.ToString());

            if (log.IsInfoEnabled) log.Info("Exiting GetService");
            return service;
        }

        /// <summary>
        /// Removes the specified service from the collection.
        /// </summary>
        public void RemoveService(Type serviceType) {
            if (log.IsInfoEnabled) log.Info("Entered RemoveService");
            if (log.IsDebugEnabled) log.Debug("Removing: " + serviceType.ToString());
            services.Remove(serviceType);
            if (log.IsInfoEnabled) log.Info("Exiting RemoveService");
        }
    }
}
